package com.jyb.qiyefuwu.view.fragment.usercenter;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jyb.qiyefuwu.R;
import com.jyb.qiyefuwu.databinding.FragmentSalelistBinding;
import com.jyb.qiyefuwu.entity.MakeOverOrderEntity;
import com.jyb.qiyefuwu.eventmodel.ContantsEventMessageCode;
import com.jyb.qiyefuwu.eventmodel.MakOverOrderDeleteItemEvent;
import com.jyb.qiyefuwu.eventmodel.UpdateSaleListEvent;
import com.jyb.qiyefuwu.uitls.DialogFunction;
import com.jyb.qiyefuwu.uitls.DialogHelper;
import com.jyb.qiyefuwu.uitls.DialogTextReturnValue;
import com.jyb.qiyefuwu.uitls.PointUtils;
import com.jyb.qiyefuwu.view.activity.usercenter.SalesOrderDetailsActivity;
import com.jyb.qiyefuwu.view.adpater.MakeOverOrderAdpter;
import com.jyb.qiyefuwu.viewmodel.SaleListViewModel;
import com.sgb.link.router.PathCapital;
import com.sgb.link.router.PathEnterpriseServices;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.common.base.BaseViewModel;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class SaleOrderListFragment extends AppLazyFragment {

    private FragmentSalelistBinding mBinding;
    private SaleListViewModel mViewModel;
    private MakeOverOrderAdpter madpater;

    /**
     * @param orderStatus   普通订单:1待结单 2待支付 3已关闭 4交易中
     * @param buyerOrSeller 0销售订单 1采购订单 用户中心订单列表必传参数
     * @param orderType     1表示商标转让 2表示专利转让 3表示版权转让
     * @return
     */
    public static SaleOrderListFragment newInstance(int orderStatus, int buyerOrSeller, int orderType) {
        SaleOrderListFragment fragment = new SaleOrderListFragment();
        Bundle mbundle = new Bundle();
        mbundle.putInt("orderStatus", orderStatus);
        mbundle.putInt("buyerOrSeller", buyerOrSeller);
        mbundle.putInt("orderType", orderType);
        fragment.setArguments(mbundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_salelist, container, false);
        mViewModel = new ViewModelProvider(this).get(SaleListViewModel.class);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        super.initView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mViewModel.orderStatus = getArguments().getInt("orderStatus", 1);
        mViewModel.buyerOrSeller = getArguments().getInt("buyerOrSeller", 0);
        mViewModel.orderType = getArguments().getInt("orderType", 1);
        inintRecyclerView();
        initObsever();
        mViewModel.getData(false);
        mViewModel.getUserWallet();

    }

    private void inintRecyclerView() {
        ((TextView)mBinding.layputNull.findViewById(R.id.no_data_tv)).setTextColor(Color.parseColor("#333333"));
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        madpater = new MakeOverOrderAdpter(getActivity());
        madpater.setBuyerOrSeller(mViewModel.buyerOrSeller);
        mBinding.recyclerView.setAdapter(madpater);
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mViewModel.getData(false);
            }

            @Override
            public void onLoadMore() {
                mViewModel.getData(true);
            }
        });
        madpater.setOnItemClick(new AdapterOnItemClick<MakeOverOrderEntity>() {
            @Override
            public void onItemClick(MakeOverOrderEntity makeOverOrderEntity, int position) {
                if (!ClickUtils.isDoubleClick()) {
                    switch (position) {
                        case MakeOverOrderAdpter.CLICK_SALE_COLOSEORDER:

                            DialogHelper.showDialog(getActivity(), "关闭订单", true, "请输入关闭订单的原因", 200, true, new DialogTextReturnValue() {
                                @Override
                                public void returnvalue(String value, Dialog dialog) {
                                    dialog.dismiss();
                                    mViewModel.ColoseOrder(makeOverOrderEntity.getId() + "", value, true);
                                }
                            });

                            break;
                        case MakeOverOrderAdpter.CLICK_SALE_CONFRIMORDER:
                            if (mViewModel.process_type == -1) {
                                mViewModel.mToast.postValue("获取开户信息失败");
                                return;
                            }
                            if (mViewModel.process_type == 2 || mViewModel.process_type == 4) {//已开户

                                DialogHelper.showDialog(getActivity(),
                                        "重要提示",
                                        "确认接收该订单，若接单后，出现因卖方原因而造成异常订单，一律由卖方承担违约金（包括且不限于卖方损失费用、三方支付平台手续费等）。",
                                        "不了，我再看看",
                                        "明白仍要接单",
                                        new DialogFunction() {
                                            @Override
                                            public void normalRoundDialog() {
                                                mViewModel.ConFrimOrder(makeOverOrderEntity.getId() + "");
                                            }
                                        });
                            } else {
                                int muser_type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
                                switch (muser_type) {
                                    case 0://个人
                                        DialogHelper.showDialog(getActivity(),
                                                "无法接单",
                                                "请先开通商家资金账户",
                                                "商家资金账户开通后，销售订单可使用在线收款，支持网银收款、快捷支付收款等。",
                                                "前往“资金中心”处理 ",
                                                "取消",
                                                "立即前往",
                                                new DialogFunction() {
                                                    @Override
                                                    public void normalRoundDialog() {

                                                        ActivityJump.startActivity(PathCapital.OpenAccountFirstActivity,
                                                                Pair.create("isUser", muser_type == 0));
                                                    }
                                                }
                                        );
                                        break;
                                    case 1://公司
                                        DialogHelper.showDialog(getActivity(),
                                                "无法接单",
                                                "请先开通商家资金账户",
                                                "商家资金账户开通后，销售订单可使用在线收款，支持企业网银收款、快捷支付收款等。",
                                                "前往“资金中心”处理 ",
                                                "取消",
                                                "立即前往",
                                                new DialogFunction() {
                                                    @Override
                                                    public void normalRoundDialog() {

                                                        ActivityJump.startActivity(PathCapital.OpenAccountFirstActivity,
                                                                Pair.create("isUser", muser_type == 0));
                                                    }
                                                }
                                        );
                                        break;
                                    case 2://团队
                                        DialogHelper.showDialog(getActivity(),
                                                "无法接单",
                                                "请先开通商家资金账户",
                                                "商家资金账户开通后，销售订单可使用在线收款，支持网银收款、快捷支付收款等。",
                                                "请切换为个人身份，前往【资金中心】进行开户。",
                                                "",
                                                "确认",
                                                new DialogFunction() {
                                                    @Override
                                                    public void normalRoundDialog() {

                                                        ActivityJump.startActivity(PathCapital.OpenAccountFirstActivity,
                                                                Pair.create("isUser", muser_type == 0));
                                                    }
                                                }
                                        );
                                        break;
                                }

                            }

                            break;
                        case MakeOverOrderAdpter.CLICK_PURCHASE_COLOSEORDER:
                            DialogHelper.showDialog(getActivity(), "取消订单", true, "请输入取消订单的原因", 200, true, new DialogTextReturnValue() {
                                @Override
                                public void returnvalue(String value, Dialog dialog) {
                                    dialog.dismiss();
                                    mViewModel.ColoseOrder(makeOverOrderEntity.getId() + "", value, false);
                                }
                            });
                            break;
                        case MakeOverOrderAdpter.CLICK_DELETEORDER:

                            DialogHelper.showDialog(getActivity(), "温馨提示", "是否删除该订单？", "取消", "确定", new DialogFunction() {
                                @Override
                                public void normalRoundDialog() {
                                    mViewModel.deleteOrder(makeOverOrderEntity.getId() + "");
                                }
                            });

                            break;


                        case MakeOverOrderAdpter.CLICK_PURCHASE_PAYOFF_COLOSEORDER:
                            DialogHelper.showDialog(getActivity(), "取消订单", true, "请输入取消订单的原因", 200, true, new DialogTextReturnValue() {
                                @Override
                                public void returnvalue(String value, Dialog dialog) {
                                    dialog.dismiss();
                                    mViewModel.ColoseOrder(makeOverOrderEntity.getId() + "", value, false);
                                }
                            });
                            break;

                        case MakeOverOrderAdpter.CLICK_PURCHASE_PAYOFF_GOTOPAY:


                            if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 1) {//公司
                                mViewModel.choiceItem = makeOverOrderEntity;
//                                mViewModel.getCompanyType(0);
                                mViewModel.getOrderStatus(0);
                            } else {//团队和个人
                                mViewModel.choiceItem = makeOverOrderEntity;
                                DialogHelper.showDialog(getActivity(), "重要提示", "确认支付该订单，若支付后，出现因买方原因而造成异常订单，一律由买方承担违约金（包括且不限于卖方损失费用、三方支付平台手续费等）。", "不了，我再看看", "明白，仍要支付", new DialogFunction() {
                                    @Override
                                    public void normalRoundDialog() {
                                        mViewModel.CreatePayOrderForUser(0);
                                    }
                                });
                            }

                            break;


                        case MakeOverOrderAdpter.CLICK_PURCHASE_CONFIRM_SERSS:
                            DialogHelper.showDialog(getActivity(), new DialogFunction() {
                                @Override
                                public void normalRoundDialog() {
                                    mViewModel.choiceItem = makeOverOrderEntity;
                                    mViewModel.confirmOderComplete(0);
                                }
                            });
                            break;
                        case MakeOverOrderAdpter.CLICK_SALEORDER_SUBMIT_DATA:
                            ActivityJump.startActivity(PathEnterpriseServices.VoucherActivity, Pair.create("oderId", makeOverOrderEntity.getOrderId()),
                                    Pair.create("isGone", false), Pair.create("status", makeOverOrderEntity.getProcessStatus()+""),Pair.create("isList", true));
                            break;

                        default:
                            if (mViewModel.buyerOrSeller == 0) {
                                ActivityJump.startActivity(PathEnterpriseServices.SalesOrderDetailsActivity,
                                        Pair.create("zhiChanType",
                                                mViewModel.orderType == 1 ? SalesOrderDetailsActivity.TRADE_MARK :
                                                        mViewModel.orderType == 2 ? SalesOrderDetailsActivity.PATENT :
                                                                SalesOrderDetailsActivity.COPYRIGHT),
                                        Pair.create("oderId", makeOverOrderEntity.getOrderId()));
                            } else {
                                ActivityJump.startActivity(PathEnterpriseServices.PurchaseOrderDetailsActivity,
                                        Pair.create("zhiChanType",
                                                mViewModel.orderType == 1 ? SalesOrderDetailsActivity.TRADE_MARK :
                                                        mViewModel.orderType == 2 ? SalesOrderDetailsActivity.PATENT :
                                                                SalesOrderDetailsActivity.COPYRIGHT),
                                        Pair.create("oderId", makeOverOrderEntity.getOrderId()));
                            }

                            break;
                    }

                }
            }
        });
    }


    private void initObsever() {
        mViewModel.listdata.observe(this, listdata -> {

            if (mViewModel.isloadmore) {
                if (null != listdata && listdata.size() > 0) {
                    mBinding.recyclerView.loadMoreComplete();
                    madpater.addDatas(listdata);
                } else {
                    mBinding.recyclerView.setNoMore(true);
                }
                mBinding.recyclerView.setVisibility(View.VISIBLE);
            } else {
                mBinding.recyclerView.refreshComplete();
                if (listdata.size() == 0) {
                    madpater.setDatasMayNull(listdata);
                    mBinding.errorView.setVisibility(View.VISIBLE);
                } else {
                    mBinding.errorView.setVisibility(View.GONE);
                    mBinding.recyclerView.setVisibility(View.VISIBLE);
                    madpater.setDatas(listdata);
                }
            }
        });

        mViewModel.delete_item.observe(this, orderid -> {
            madpater.removeData(orderid);
            if (madpater.getDatas().size() == 0) {
//                mBinding.recyclerView.setVisibility(View.GONE);
                mBinding.errorView.setVisibility(View.VISIBLE);
            } else {
                mBinding.errorView.setVisibility(View.GONE);
//                mBinding.recyclerView.setVisibility(View.VISIBLE);
            }
        });


        mViewModel.mToast.observe(getViewLifecycleOwner(), message -> MToast.showLongToast(getActivity(), message));
        mViewModel.mLoading.observe(getViewLifecycleOwner(), type -> {
            switch (type) {
                case BaseViewModel.SHOW_LODING:
                    com.swgk.core.dialog.DialogHelper.showProgressDialog(getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    break;
                case BaseViewModel.DISMISS_LODING:
                    com.swgk.core.dialog.DialogHelper.dismissProgressDialog();
                    break;
                case BaseViewModel.FINISH_AND_DISMISS_LODING:
                    com.swgk.core.dialog.DialogHelper.dismissProgressDialog();
                    getActivity().finish();
                    break;
            }
        });

        mViewModel.approvestats.observe(this, type -> {
            switch (type) {
                case -2:
                    DialogHelper.showDialog(getActivity(), "申请提示", "该订单付款需要进行审批，是否提交付款申请？", "取消", "确定", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            ActivityJump.startActivity(PathEnterpriseServices.ApplyForPaymentActivity,
                                    Pair.create("oderId", mViewModel.choiceItem.getOrderId()),
                                    Pair.create("zhiChanType", mViewModel.orderType == 1 ? SalesOrderDetailsActivity.TRADE_MARK :
                                            mViewModel.orderType == 2 ? SalesOrderDetailsActivity.PATENT :
                                                    SalesOrderDetailsActivity.COPYRIGHT),
                                    Pair.create("sellerName", mViewModel.choiceItem.getSellerName()),
                                    Pair.create("price", PointUtils.price(mViewModel.choiceItem.getDealPrice())),
                                    Pair.create("createTime", mViewModel.choiceItem.getOrderTime() + ""),
                                    Pair.create("id", mViewModel.applyId),
                                    Pair.create("publishType", mViewModel.choiceItem.getPublishType() + ""),
                                    Pair.create("sellerNo", mViewModel.choiceItem.getSellerNo()),
                                    Pair.create("agentNo", mViewModel.choiceItem.getAgentNo()),
                                    Pair.create("agent", mViewModel.choiceItem.getAgent()));
                        }
                    });
                    break;


                case 3:
                case -1:
                    DialogHelper.showDialog(getActivity(), "审批中", "该订单已申请付款，审批通过后才可付款。", "", "确定", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {

                        }
                    });

                    break;

                case 0://审批被拒绝

                    DialogHelper.showDialog(getActivity(), "提交审核", "该订单付款申请未通过审批，是否再次发起申请？", "取消", "确定", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            ActivityJump.startActivity(PathEnterpriseServices.ApplyForPaymentActivity,
                                    Pair.create("oderId", mViewModel.choiceItem.getOrderId()),
                                    Pair.create("zhiChanType", mViewModel.orderType == 1 ? SalesOrderDetailsActivity.TRADE_MARK :
                                            mViewModel.orderType == 2 ? SalesOrderDetailsActivity.PATENT :
                                                    SalesOrderDetailsActivity.COPYRIGHT),
                                    Pair.create("sellerName", mViewModel.choiceItem.getSellerName()),
                                    Pair.create("price", PointUtils.price(mViewModel.choiceItem.getDealPrice())),
                                    Pair.create("createTime", mViewModel.choiceItem.getOrderTime() + ""),
                                    Pair.create("id", mViewModel.applyId),
                                    Pair.create("publishType", mViewModel.choiceItem.getPublishType() + ""),
                                    Pair.create("sellerNo", mViewModel.choiceItem.getSellerNo()),
                                    Pair.create("agentNo", mViewModel.choiceItem.getAgentNo()),
                                    Pair.create("agent", mViewModel.choiceItem.getAgent()));
                        }
                    });

                    break;
                case 2:
                case 1://审批通过
                    DialogHelper.showDialog(getActivity(), "审批通过", "", "", "企业用户支付请前往“资金中心-待付账单”处理", "", "我知道了", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {

                        }
                    });
                    break;

                case 4:
                    DialogHelper.showDialog(getActivity(), "申请付款", "确认提交付款申请？提交成功后，可在资金中心-待付账单进行支付",
                            "特别说明：确认支付该订单，若支付后，出现因买方原因而造成异常订单，一律由买方承担违约金（包括且不限于卖方损失费用、三方支付平台手续费等）。",
                            "取消", "确定", new DialogFunction() {
                                @Override
                                public void normalRoundDialog() {
                                    mViewModel.CreatePayOrder(0);
                                }
                            });
                    break;

                case 5:
                    DialogHelper.showDialog(getActivity(), "提示", "", "付款申请已提交", "企业用户支付请前往“资金中心-待付账单”处理", "", "我知道了", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {

                        }
                    });

                    break;

                case 6:
//                    DialogHelper.showDialog(getActivity(), "提示", "", "管理员已经开启订单付款审批流程", "企业用户支付请前往“资金中心-待付账单”处理", "", "我知道了", new DialogFunction() {
//                        @Override
//                        public void normalRoundDialog() {
//
//                        }
//                    });
                    MToast.showLongToast(getActivity(),"管理员已经开启订单付款审批流程");

                    break;


            }
        });
    }

    @Override
    protected void onLazyLoad() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteItemData(MakOverOrderDeleteItemEvent entity) {
        if (entity != null) {
            mViewModel.delete_item.postValue(entity.getItemid());
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void UpdateListdata(UpdateSaleListEvent event) {

        if (event == null) {
            return;
        }
        if(event.code!=0){
            switch (event.code){
                case ContantsEventMessageCode
                        .APPLY_TYPE_CHANGER_ANDSUBMITORDER:
                    mViewModel.CreatePayOrder(0);
                    break;
            }
        }

        if (event.getOrderStatus() == mViewModel.orderStatus && event.getBuyerOrSeller() == mViewModel.buyerOrSeller) {
            mViewModel.getData(false);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatepayEvent(Object o) {
        if (o == null) {
            return;
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(o));
        if (jsonObject.get("code") != null) {
            int code = jsonObject.getInteger("code");
            switch (code) {
                case 2://收银台返回的code
                    if (!ClickUtils.isDoubleClick() && code == 2) {
                        if (mViewModel.orderStatus == 2 && mViewModel.buyerOrSeller == 1) {
                            mViewModel.getData(false);
                        }
                    }
                    break;
                case 1000000013://支付成功
                    if (!ClickUtils.isDoubleClick() && code == 2) {
                        if (  mViewModel.buyerOrSeller == 1) {
                            if(mViewModel.orderStatus == 2||mViewModel.orderStatus == 4) {
                                mViewModel.getData(false);
                            }
                        }
                    }
                    break;

                case 1000000014://支付成功
                    if (!ClickUtils.isDoubleClick() && code == 2) {
                        if (  mViewModel.buyerOrSeller == 1) {
                            if(mViewModel.orderStatus == 2||mViewModel.orderStatus == 4) {
                                mViewModel.getData(false);
                            }
                        }
                    }
                    break;
            }

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
